package other.edan.erp.k3;


import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.data.model.LogisticsInfo__c;
import com.rkhd.platform.sdk.data.model.SnCode__c;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.edan.erp.apitool.EdanK3Utils;
import other.edan.erp.utils.HCXObjectService;
import other.edan.erp.utils.ResultBody;
import other.edan.erp.utils.ResultVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 同步物流信息
 * @Author 黎炎松
 * 2024-11-20 13:46
 */
@RestApi(baseUrl = "/edan/logistics")
public class SyncLogistics extends SyncSuper implements ScheduleJob, FutureTask {
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步K3物流信息 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncLogistics();
    }

    /**
     * 手动触发同步
     * @param
     * @return
     */
    @RestMapping(value = "/handerSync", method = RequestMethod.POST)
    public ResultVo handerSync() throws AsyncTaskException {
        LOGGER.debug("手动触发同步");
        String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
        LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        return ResultVo.success("开通同步");
    }


    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        new SyncLogistics().startSyncLogistics();
    }

    /**
     * 开始同步物流信息
     */
    public ResultVo startSyncLogistics() {
        try {
            LOGGER.debug(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取数据
            SyncConfig__c syncConfig = getSyncConfig("K3_WLXX");

            // todo
            String startDate = syncConfig.getAttribute("startDate");
            String endDate = syncConfig.getAttribute("endDate");
            startDate = "2024-01-20 00:00:00";
            endDate = "2024-02-20 00:00:00";

            // 设置参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("pageSize", "10");
            paramsMap.put("createStartDate", startDate);
            paramsMap.put("createEndDate", endDate);
            LOGGER.debug(LOGGER_MSG + " paramsMap: " + paramsMap);

            // 发送请求获取数据
            // todo (去除token)
            ResultBody response = EdanK3Utils.sendGet(paramsMap, EdanK3Utils.GET_LOGISTIC, "");
            if (!Objects.equals(response.getCode(), "200")) {
                LOGGER.debug(LOGGER_MSG + "查询k3数据异常: " + response.getMessage());
                return ResultVo.error("查询k3数据异常: " + response.getMessage());
            }

            // 获取数据 判断是否有值
            JSONObject result = (JSONObject) response.getResult();
            List<JSONObject> k3DataList = JSONObject.parseArray(result.getJSONArray("expressInfos").toJSONString(), JSONObject.class);
            LOGGER.debug(LOGGER_MSG + "查询返回的数据: " + k3DataList.size());
            if (k3DataList.size() <= 0) {
                LOGGER.debug(LOGGER_MSG + "暂无需要处理的数据");
                // 同步修改配置表
                upSyncConfig(syncConfig);
                return ResultVo.success();
            }

            // 获取系统中存在的数据
            Map<String, Long> crmLogMap = getCrmDataMap("logistics", "tracking_number", k3DataList);
            Map<String, Long> crmSalOutMap = getCrmDataMap("saleOut", "fbillNo", k3DataList);
            Map<String, Long> crmOrderMap = getCrmDataMap("k3CodeOrder", "forderBillNo", k3DataList);

            // 获取新增、修改的数据
            List<LogisticsInfo__c> crmAddList = new ArrayList<>(); // CRM新增集合
            List<LogisticsInfo__c> crmUpList = new ArrayList<>(); // CRM修改集合
            for (JSONObject k3Data : k3DataList) {
                // 处理出库
                LogisticsInfo__c logistics = new LogisticsInfo__c();
                String number = k3Data.getString("tracking_number");

                logistics.setEntityType(3533379737983579L);
                logistics.setEdanId__c(k3Data.getString("t_id")); // 数据id
                logistics.setName(number); // 运单号
                logistics.setSalesOutReceipt__c(crmSalOutMap.get(k3Data.getString("fbillNo"))); // 出库单
                //logistics.setName(number); // 出库单明细 --
                logistics.setOrderCode__c(crmOrderMap.get(k3Data.getString("forderBillNo"))); // 订单单号
                logistics.setContractCodes__c(k3Data.getString("fheadSelfS0153")); // 正式合同编号
                logistics.setGeneralCarrier__c(k3Data.getString("carrier")); // 承运商
                logistics.setWaybillNumber__c(k3Data.getString("number")); // 运单号
                logistics.setDeliveryDate__c(getDateVal(k3Data.getString("delivery_date"),3)); // 发货日期 --
                logistics.setModeOfTransport__c(k3Data.getString("transport")); // 运输方式
                logistics.setAddressee__c(k3Data.getString("addressee")); // 收件人
                logistics.setTelephone__c(k3Data.getString("phone")); // 电话
                logistics.setAddress__c(k3Data.getString("delivery_address")); // 收货地址
                logistics.setNumberOfParcels__c(k3Data.getDouble("packages_qty")); // 包裹件数
                logistics.setRemark__c(k3Data.getString("description")); // 备注

                // 判断系统中是否存在，存在则更新
                LOGGER.debug(LOGGER_MSG + "snCode = " + logistics);
                if (crmLogMap.containsKey(number)) {
                    logistics.setId(crmLogMap.get(number));
                    crmUpList.add(logistics);
                } else {
                    crmAddList.add(logistics);
                }

                // 进行新增、更新
                if (crmAddList.size() >= 100) {
                    HCXObjectService.updateBatch(crmAddList);
                    crmAddList.clear();
                }
                if (crmUpList.size() >= 100) {
                    HCXObjectService.updateBatch(crmUpList);
                    crmUpList.clear();
                }
            }

            // 进行批量新增、更新
            HCXObjectService.insertBatch(crmAddList);
            HCXObjectService.updateBatch(crmUpList);

            // 更新同步配置
            upSyncConfig(syncConfig);

            LOGGER.debug(LOGGER_MSG + "处理成功");
            return ResultVo.success();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常: " + e.getMessage());
        }
    }



}
